/*
 * Created by Huang 嵘才 on 18-5-10 下午3:51
 * Copyright (c) 2018. All rights reserved.
 * Last modified 18-5-10 下午3:51
 */

package io.esirong

import android.app.Activity
import android.os.Build
import java.lang.ref.WeakReference
import java.util.*

/**
 * 应用程序Activity管理类：用于Activity管理和应用程序退出
 * Activity管理.1。获取，添加，删除，关闭等
 * <P>使用弱引用保存Activity实例</P>
 */
object ActivityManager {
    private val mActivityStack = Stack<WeakReference<Activity>>()

    /**
     * 获取当前的Activity
     *
     * @return Activity
     */
    fun getCurrentActivity(): Activity? {
        return if (mActivityStack.empty()) {
            null
        } else mActivityStack.peek().get()
    }

    /**
     * activity是不是处于可以正常使用情况
     *
     * @return 可以正常使用
     */
    fun activityIsAlive(activity: Activity?): Boolean {
        if (activity == null) {
            return false
        }
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            !(activity.isDestroyed || activity.isFinishing)
        } else {
            !activity.isFinishing
        }
    }

    /**
     * 添加activity 到一个管理的列表中
     *
     * @param activity activity
     */
    fun addActivity(activity: Activity?) {
        if (activity != null) {
            mActivityStack.push(WeakReference(activity))
        }
    }

    /**
     * 移除 activity 从一个管理的列表中
     *
     * @param activity activity
     */
    fun removeActivity(activity: Activity) {
        remove(activity)
    }

    /**
     * 删除当前的activity
     */
    fun removeCurrent() {
        val activity = getCurrentActivity()
        remove(activity)
    }

    /**
     * 移除所有的Activity
     */
    fun removeAll() {
        for (i in mActivityStack.indices.reversed()) {
            mActivityStack.removeAt(i)
        }
    }

    /**
     * 结束当前Activity（堆栈中最后一个压入的）
     */
    fun finishActivity() {
        val activity: Activity? = getCurrentActivity();
        finishActivity(activity)
    }

    /**
     * 结束指定的Activity
     */
    fun finishActivity(activity: Activity?) {
        var activity = activity
        if (activity != null) {
            activity.finish()
            activity = null
        }
    }

    /**
     * 结束指定类名的Activity
     */
    fun finishActivity(cls: Class<*>) {
        for (activity in mActivityStack) {
            if (activity.get() == cls) {
                finishActivity(activity.get())
            }
        }
    }

    /**
     * 移除&关闭所有的Activity
     */
    fun finishAll() {
        tryClearNullReference()
        for (i in mActivityStack.indices.reversed()) {
            val aActivity = mActivityStack[i].get()
            if (aActivity != null) {
                mActivityStack.removeAt(i)
                aActivity.finish()
            }
        }
    }

    /**
     * 获取列表中大小
     *
     * @return 大小
     */
    fun size(): Int {
        return mActivityStack.size
    }

    /**
     * 移除指定的Activity
     *
     * @param activity activity
     */
    private fun remove(activity: Activity?) {
        tryClearNullReference()
        if (activity != null) {
            for (i in mActivityStack.indices.reversed()) {
                val aActivity = mActivityStack[i].get()
                if (aActivity != null) {
                    if (aActivity == activity) {
                        mActivityStack.removeAt(i)
                    }
                }
            }
        }
    }

    private fun tryClearNullReference() {
        for (weakReference in mActivityStack) {
            val aActivity = weakReference.get()
            if (aActivity == null) {
                mActivityStack.remove(weakReference)
            }
        }
    }
}